package http;

import core.Handler;
import core.HandlerContext;
import core.TemplateHandler;

import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;

public class HttpCodecHandler extends TemplateHandler implements Handler {

    private byte[] getByteBuffer(ByteBuffer buff){
        System.out.println("position:"+buff.position()+"\t limit:"+buff.limit());
        int limit = buff.limit();
        byte[] content = new byte[limit];
        buff.get(content);
        return content;
    }
    @Override
    public void channelRead(HandlerContext ctx, Object msg) {
        super.channelRead(ctx,msg);
        ByteBuffer buffer=(ByteBuffer) msg;
        ctx.channel.doReadQueue(getByteBuffer(buffer));
        ctx.channel.markReadQueue();
        byte[] bytes=ctx.channel.getReadQueue();
        HttpRequest httpRequest = new HttpRequest();

        if (httpRequest.checkHttpMessage(bytes) && bytes.length > HttpMessage.maxsize) {
            this.write(ctx,HttpResponse.buildErrorMessage(413));
            // 刷新回复
            this.flush(ctx); //传递到头节点
            return;
        }
        //判断是否接收完成,非HTTP要根据约定结束符号判断
        if (httpRequest.checkHttpMessage(bytes)) {
            int remainSize= httpRequest.parse(bytes);
            System.out.println("remainSize:"+remainSize);
            if (remainSize < 0) {
                ctx.channel.resetReadQueue();
            } else {
                // 放入剩余字节
                if (remainSize>0) ctx.channel.moveReadQueue(remainSize);
                // 传递给下一个
                ctx.ChannelRead(httpRequest);
            }
        }

    }

    @Override
    public void write(HandlerContext ctx, Object msg) {
        // 转 byteBuffer
        super.write(ctx,msg);
        if (msg instanceof byte[] buf) {
            System.out.println("byte数组编码: "+buf.length);
            ByteBuffer wrap = ByteBuffer.wrap(buf);
            ctx.write(wrap);
        }
        else if (msg instanceof ByteBuffer wrap) {
            System.out.println("ByteBuffer编码");
            ctx.write(wrap);
        }
        else {
            System.out.println("字符串编码：\n"+msg.toString());
            ByteBuffer wrap = ByteBuffer.wrap(msg.toString().getBytes(StandardCharsets.UTF_8));
            // 传递给上一个
            ctx.write(wrap);
        }
    }

    @Override
    public void flush(HandlerContext ctx) {
        super.flush(ctx);
        ctx.flush();
    }
}
